// 常量
const STORAGE_KEYS = {
    TASKS: 'zen_focus_tasks',
    SETTINGS: 'zen_focus_settings',
    THEME: 'zen_focus_theme',
    STATS: 'zen_focus_stats'
};

const DEFAULT_SETTINGS = {
    workDuration: 25,
    breakDuration: 5,
    soundNotification: true,
    desktopNotification: true,
    autoStartBreak: false,
    autoStartWork: false
};

// 工具函数
const utils = {
    formatTime(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },

    showNotification(title, options = {}) {
        if (!('Notification' in window)) return;
        
        if (Notification.permission === 'granted') {
            new Notification(title, options);
        } else if (Notification.permission !== 'denied') {
            Notification.requestPermission().then(permission => {
                if (permission === 'granted') {
                    new Notification(title, options);
                }
            });
        }
    },

    playSound(soundName) {
        const audio = new Audio(`sounds/${soundName}.mp3`);
        audio.play();
    }
};

// 主题管理
const ThemeManager = {
    init() {
        this.themeToggle = document.getElementById('themeToggle');
        this.loadTheme();
        this.bindEvents();
    },

    loadTheme() {
        const savedTheme = localStorage.getItem(STORAGE_KEYS.THEME) || 'light';
        document.documentElement.setAttribute('data-theme', savedTheme);
        this.updateThemeIcon(savedTheme);
    },

    bindEvents() {
        this.themeToggle.addEventListener('click', () => {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem(STORAGE_KEYS.THEME, newTheme);
            this.updateThemeIcon(newTheme);
        });
    },

    updateThemeIcon(theme) {
        const icon = this.themeToggle.querySelector('i');
        icon.className = theme === 'light' ? 'fas fa-moon' : 'fas fa-sun';
    }
};

// 番茄钟管理
const PomodoroManager = {
    init() {
        this.settings = { ...DEFAULT_SETTINGS };
        this.currentTime = this.settings.workDuration * 60;
        this.isRunning = false;
        this.isWorkTime = true;
        this.completedPomodoros = 0;
        this.totalFocusTime = 0;

        this.initializeElements();
        this.loadSettings();
        this.bindEvents();
        this.updateDisplay();
        this.updateProgress();
    },

    initializeElements() {
        this.elements = {
            timeDisplay: document.getElementById('timeDisplay'),
            phaseDisplay: document.getElementById('phaseDisplay'),
            startBtn: document.getElementById('startTimer'),
            resetBtn: document.getElementById('resetTimer'),
            skipBtn: document.getElementById('skipTimer'),
            progressRing: document.querySelector('.progress-ring-circle'),
            todayPomodoros: document.getElementById('todayPomodoros'),
            totalFocusTime: document.getElementById('totalFocusTime')
        };

        // 设置进度环
        const circle = this.elements.progressRing;
        const radius = circle.r.baseVal.value;
        this.circumference = radius * 2 * Math.PI;
        circle.style.strokeDasharray = `${this.circumference} ${this.circumference}`;
    },

    bindEvents() {
        this.elements.startBtn.addEventListener('click', () => this.toggleTimer());
        this.elements.resetBtn.addEventListener('click', () => this.reset());
        this.elements.skipBtn.addEventListener('click', () => this.skip());
    },

    toggleTimer() {
        if (this.isRunning) {
            this.pause();
        } else {
            this.start();
        }
    },

    start() {
        if (!this.isRunning) {
            this.isRunning = true;
            this.updateControls(true);
            
            this.timer = setInterval(() => {
                this.currentTime--;
                this.updateDisplay();
                this.updateProgress();

                if (this.currentTime <= 0) {
                    this.completeInterval();
                }
            }, 1000);
        }
    },

    pause() {
        if (this.isRunning) {
            this.isRunning = false;
            clearInterval(this.timer);
            this.updateControls(false);
        }
    },

    reset() {
        this.pause();
        this.currentTime = this.isWorkTime ? 
            this.settings.workDuration * 60 : 
            this.settings.breakDuration * 60;
        this.updateDisplay();
        this.updateProgress();
    },

    skip() {
        this.completeInterval();
    },

    completeInterval() {
        this.pause();
        
        if (this.isWorkTime) {
            this.completedPomodoros++;
            this.totalFocusTime += this.settings.workDuration;
            this.updateStats();
            
            if (this.settings.soundNotification) {
                utils.playSound('complete');
            }
            
            if (this.settings.desktopNotification) {
                utils.showNotification('专注时间结束', {
                    body: '该休息一下了！',
                    icon: '/icon.png'
                });
            }

            this.isWorkTime = false;
            this.currentTime = this.settings.breakDuration * 60;
            
            if (this.settings.autoStartBreak) {
                this.start();
            }
        } else {
            this.isWorkTime = true;
            this.currentTime = this.settings.workDuration * 60;
            
            if (this.settings.desktopNotification) {
                utils.showNotification('休息时间结束', {
                    body: '准备开始新的专注！',
                    icon: '/icon.png'
                });
            }

            if (this.settings.autoStartWork) {
                this.start();
            }
        }

        this.updateDisplay();
        this.updateProgress();
    },

    updateDisplay() {
        this.elements.timeDisplay.textContent = utils.formatTime(this.currentTime);
        this.elements.phaseDisplay.textContent = this.isWorkTime ? '专注时间' : '休息时间';
    },

    updateProgress() {
        const totalTime = this.isWorkTime ? 
            this.settings.workDuration * 60 : 
            this.settings.breakDuration * 60;
        const progress = this.currentTime / totalTime;
        const offset = this.circumference - (progress * this.circumference);
        this.elements.progressRing.style.strokeDashoffset = offset;
    },

    updateControls(isRunning) {
        const startIcon = this.elements.startBtn.querySelector('i');
        startIcon.className = isRunning ? 'fas fa-pause' : 'fas fa-play';
        this.elements.startBtn.classList.toggle('active', isRunning);
    },

    updateStats() {
        this.elements.todayPomodoros.textContent = this.completedPomodoros;
        this.elements.totalFocusTime.textContent = `${this.totalFocusTime}分钟`;
        this.saveStats();
    },

    loadSettings() {
        const savedSettings = localStorage.getItem(STORAGE_KEYS.SETTINGS);
        if (savedSettings) {
            this.settings = { ...this.settings, ...JSON.parse(savedSettings) };
        }
    },

    saveSettings() {
        localStorage.setItem(STORAGE_KEYS.SETTINGS, JSON.stringify(this.settings));
    },

    loadStats() {
        const savedStats = localStorage.getItem(STORAGE_KEYS.STATS);
        if (savedStats) {
            const stats = JSON.parse(savedStats);
            this.completedPomodoros = stats.completedPomodoros;
            this.totalFocusTime = stats.totalFocusTime;
            this.updateStats();
        }
    },

    saveStats() {
        const stats = {
            completedPomodoros: this.completedPomodoros,
            totalFocusTime: this.totalFocusTime
        };
        localStorage.setItem(STORAGE_KEYS.STATS, JSON.stringify(stats));
    }
};

// 任务管理
const TaskManager = {
    tasks: [],

    init() {
        this.initializeElements();
        this.loadTasks();
        this.bindEvents();
        this.renderTasks();
    },

    initializeElements() {
        this.elements = {
            taskList: document.getElementById('taskList'),
            addTaskBtn: document.getElementById('addTaskBtn'),
            taskModal: document.getElementById('taskModal'),
            taskForm: document.getElementById('taskForm'),
            saveTaskBtn: document.getElementById('saveTaskBtn'),
            completedTasks: document.getElementById('completedTasks')
        };
    },

    bindEvents() {
        this.elements.addTaskBtn.addEventListener('click', () => {
            this.elements.taskModal.classList.add('active');
        });

        this.elements.saveTaskBtn.addEventListener('click', () => this.saveTask());

        document.querySelectorAll('.close-modal').forEach(btn => {
            btn.addEventListener('click', () => {
                this.elements.taskModal.classList.remove('active');
            });
        });
    },

    saveTask() {
        const form = this.elements.taskForm;
        const title = form.querySelector('#taskTitle').value;
        const pomodoros = parseInt(form.querySelector('#taskPomodoros').value);
        const priority = form.querySelector('#taskPriority').value;
        const notes = form.querySelector('#taskNotes').value;

        if (title) {
            const task = {
                id: Date.now(),
                title,
                pomodoros,
                priority,
                notes,
                completed: false,
                createdAt: new Date().toISOString()
            };

            this.tasks.unshift(task);
            this.saveTasks();
            this.renderTasks();
            this.elements.taskModal.classList.remove('active');
            form.reset();
        }
    },

    toggleTask(id) {
        const task = this.tasks.find(t => t.id === id);
        if (task) {
            task.completed = !task.completed;
            this.saveTasks();
            this.renderTasks();
            this.updateTaskStats();
        }
    },

    deleteTask(id) {
        this.tasks = this.tasks.filter(t => t.id !== id);
        this.saveTasks();
        this.renderTasks();
        this.updateTaskStats();
    },

    renderTasks() {
        this.elements.taskList.innerHTML = '';
        
        this.tasks.forEach(task => {
            const taskElement = document.createElement('div');
            taskElement.className = `task-item priority-${task.priority}`;
            taskElement.innerHTML = `
                <input type="checkbox" ${task.completed ? 'checked' : ''}>
                <div class="task-content">
                    <div class="task-title">${task.title}</div>
                    <div class="task-meta">
                        <span><i class="fas fa-clock"></i> ${task.pomodoros}</span>
                    </div>
                </div>
                <button class="delete-task">
                    <i class="fas fa-times"></i>
                </button>
            `;

            const checkbox = taskElement.querySelector('input');
            checkbox.addEventListener('change', () => this.toggleTask(task.id));

            const deleteBtn = taskElement.querySelector('.delete-task');
            deleteBtn.addEventListener('click', () => this.deleteTask(task.id));

            this.elements.taskList.appendChild(taskElement);
        });

        this.updateTaskStats();
    },

    updateTaskStats() {
        const completed = this.tasks.filter(t => t.completed).length;
        const total = this.tasks.length;
        this.elements.completedTasks.textContent = `${completed}/${total}`;
    },

    loadTasks() {
        const savedTasks = localStorage.getItem(STORAGE_KEYS.TASKS);
        if (savedTasks) {
            this.tasks = JSON.parse(savedTasks);
        }
    },

    saveTasks() {
        localStorage.setItem(STORAGE_KEYS.TASKS, JSON.stringify(this.tasks));
    }
};

// 白噪音管理
const SoundManager = {
    sounds: {},

    init() {
        this.initializeSounds();
        this.bindEvents();
    },

    initializeSounds() {
        const soundItems = document.querySelectorAll('.sound-item');
        
        soundItems.forEach(item => {
            const soundId = item.dataset.sound;
            const audio = new Audio(`sounds/${soundId}.mp3`);
            audio.loop = true;

            this.sounds[soundId] = {
                audio,
                isPlaying: false,
                volume: 0.5
            };

            const button = item.querySelector('.sound-toggle');
            const slider = item.querySelector('input[type="range"]');

            button.addEventListener('click', () => this.toggleSound(soundId, button));
            slider.addEventListener('input', (e) => this.updateVolume(soundId, e.target.value / 100));
        });
    },

    bindEvents() {
        const masterVolume = document.getElementById('masterVolume');
        masterVolume.addEventListener('click', () => {
            const icon = masterVolume.querySelector('i');
            const isMuted = icon.classList.contains('fa-volume-mute');
            
            Object.values(this.sounds).forEach(sound => {
                if (sound.isPlaying) {
                    sound.audio.volume = isMuted ? sound.volume : 0;
                }
            });

            icon.className = isMuted ? 'fas fa-volume-up' : 'fas fa-volume-mute';
        });
    },

    toggleSound(soundId, button) {
        const sound = this.sounds[soundId];
        
        if (sound.isPlaying) {
            sound.audio.pause();
            sound.isPlaying = false;
            button.classList.remove('active');
        } else {
            sound.audio.play();
            sound.isPlaying = true;
            button.classList.add('active');
        }
    },

    updateVolume(soundId, value) {
        const sound = this.sounds[soundId];
        sound.volume = value;
        sound.audio.volume = value;
    }
};

// 设置管理
const SettingsManager = {
    init() {
        this.initializeElements();
        this.bindEvents();
        this.loadSettings();
    },

    initializeElements() {
        this.elements = {
            settingsBtn: document.getElementById('settingsBtn'),
            settingsModal: document.getElementById('settingsModal'),
            saveSettingsBtn: document.getElementById('saveSettingsBtn')
        };
    },

    bindEvents() {
        this.elements.settingsBtn.addEventListener('click', () => {
            this.elements.settingsModal.classList.add('active');
        });

        this.elements.saveSettingsBtn.addEventListener('click', () => this.saveSettings());

        document.querySelectorAll('.close-modal').forEach(btn => {
            btn.addEventListener('click', () => {
                this.elements.settingsModal.classList.remove('active');
            });
        });
    },

    loadSettings() {
        const savedSettings = localStorage.getItem(STORAGE_KEYS.SETTINGS);
        if (savedSettings) {
            const settings = JSON.parse(savedSettings);
            Object.entries(settings).forEach(([key, value]) => {
                const element = document.getElementById(key);
                if (element) {
                    if (element.type === 'checkbox') {
                        element.checked = value;
                    } else {
                        element.value = value;
                    }
                }
            });
        }
    },

    saveSettings() {
        const settings = {
            workDuration: parseInt(document.getElementById('workDuration').value),
            breakDuration: parseInt(document.getElementById('breakDuration').value),
            soundNotification: document.getElementById('soundNotification').checked,
            desktopNotification: document.getElementById('desktopNotification').checked,
            autoStartBreak: document.getElementById('autoStartBreak').checked,
            autoStartWork: document.getElementById('autoStartWork').checked
        };

        localStorage.setItem(STORAGE_KEYS.SETTINGS, JSON.stringify(settings));
        PomodoroManager.settings = settings;
        PomodoroManager.reset();
        
        this.elements.settingsModal.classList.remove('active');
    }
};

// 移动端支持
const MobileSupport = {
    init() {
        this.initializeElements();
        this.bindEvents();
    },

    initializeElements() {
        this.elements = {
            menuToggle: document.getElementById('menuToggle'),
            sidePanel: document.getElementById('sidePanel')
        };
    },

    bindEvents() {
        this.elements.menuToggle.addEventListener('click', () => {
            this.elements.sidePanel.classList.toggle('active');
        });

        // 点击主内容区域时关闭侧边栏
        document.querySelector('.main-content').addEventListener('click', () => {
            if (window.innerWidth <= 768) {
                this.elements.sidePanel.classList.remove('active');
            }
        });
    }
};

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    ThemeManager.init();
    PomodoroManager.init();
    TaskManager.init();
    SoundManager.init();
    SettingsManager.init();
    MobileSupport.init();
});
